package cn.com.generaldata.os.service.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import cn.com.generaldata.os.constant.FilterConstant;
import cn.com.generaldata.os.dao.intf.BaseDAOInterface;
import cn.com.generaldata.os.newpojo.ReportType;
import cn.com.generaldata.os.paging.Event;
import cn.com.generaldata.os.paging.Filter;
import cn.com.generaldata.os.paging.FilterRule;
import cn.com.generaldata.os.paging.Page;
import cn.com.generaldata.os.paging.Result;
import cn.com.generaldata.os.pojo.DustryReport;
import cn.com.generaldata.os.pojo.EnterpriseIndustry;
import cn.com.generaldata.os.pojo.Industry;
import cn.com.generaldata.os.pojo.UserIndustry;

@Component
public class IndustryService {

	private static Logger log = LoggerFactory.getLogger(IndustryService.class);
	private static final String DUPLICATE_INDUSTRY = "duplicate";

	@Autowired
	@Qualifier("baseDAO")
	private BaseDAOInterface<Industry> industryDAO;

	@Autowired
	@Qualifier("baseDAO")
	private BaseDAOInterface<DustryReport> dustryReportDAO;

	@Autowired
	@Qualifier("baseDAO")
	private BaseDAOInterface<UserIndustry> userIndustryDAO;

	@Autowired
	@Qualifier("baseDAO")
	private BaseDAOInterface<EnterpriseIndustry> enterpriseIndustryDAO;

	public String createIndustry(Industry industry, List<ReportType> reportTypes) {
		if (industry == null || StringUtils.isBlank(industry.getDustryName())) {
			// throw new
			// CommonException(ExceptionConstant.MSG_ILLEGAL_PARAMETER);
			log.error("userId为空");
			return null;
		}

		// 判断专业名称是否重复
		Industry existIndustry = checkIndustryName(industry.getDustryName().trim());
		if (existIndustry != null) {
			// throw new
			// CommonException(ExceptionConstant.MSG_DUPLICATE_INDUSTRY_NAME);
			log.error("已存在此名称的行业");
			return null;
		}
		Filter filter3 = new Filter();
		filter3.addRule(new FilterRule(FilterConstant.EQUAL, "dl", industry.getDl().trim()));
		filter3.addRule(new FilterRule(FilterConstant.EQUAL, "zl", industry.getZl().trim()));
		filter3.addRule(new FilterRule(FilterConstant.EQUAL, "xl", industry.getXl().trim()));
		List<Industry> find2 = industryDAO.find(Industry.class, filter3, null);
		if (find2 != null && find2.size() > 0) {
			// throw new
			// CommonException(ExceptionConstant.MSG_ILLEGAL_PARAMETER);
			log.error("已存在该类别行业");
			return null;
		}
		if (industry.getId() == null || "".equals(industry.getId()))
			industry.setId(UUID.randomUUID().toString().replaceAll("-", ""));
		industryDAO.save(industry);

		// 保存专业与报表类型的关系
		Set<DustryReport> dustryReports = new HashSet<DustryReport>();
		if (reportTypes != null && reportTypes.size() > 0) {
			for (ReportType reportType : reportTypes) {
				DustryReport dustryReport = new DustryReport(UUID.randomUUID().toString().replaceAll("-", ""), industry, reportType.getId());
				dustryReportDAO.save(dustryReport);
				dustryReports.add(dustryReport);
			}
			industry.setDustryReports(dustryReports);
		}
		return industry.getId();
	}

	public Industry modifyIndustry(Industry industry, List<ReportType> reportTypes, String[] noReportTypes) {
		if (industry == null || StringUtils.isBlank(industry.getDustryName())) {
			// throw new
			// CommonException(ExceptionConstant.MSG_ILLEGAL_PARAMETER);
			log.error("industry为空");
			return null;
		}
		Filter filter2 = new Filter();
		filter2.addRule(new FilterRule(FilterConstant.EQUAL, "dustryName", industry.getDustryName().trim()));
		filter2.addRule(new FilterRule(FilterConstant.NOT_EQUAL, "id", industry.getId()));
		List<Industry> find = industryDAO.find(Industry.class, filter2, null);
		if (find != null && find.size() > 0) {
			// throw new
			// CommonException(ExceptionConstant.MSG_ILLEGAL_PARAMETER);
			log.error("已存在此名称的行业");
			return null;
		}
		Filter filter3 = new Filter();
		filter3.addRule(new FilterRule(FilterConstant.EQUAL, "dl", industry.getDl().trim()));
		filter3.addRule(new FilterRule(FilterConstant.EQUAL, "zl", industry.getZl().trim()));
		filter3.addRule(new FilterRule(FilterConstant.EQUAL, "xl", industry.getXl().trim()));
		filter3.addRule(new FilterRule(FilterConstant.NOT_EQUAL, "id", industry.getId()));
		List<Industry> find2 = industryDAO.find(Industry.class, filter3, null);
		if (find2 != null && find2.size() > 0) {
			// throw new
			// CommonException(ExceptionConstant.MSG_ILLEGAL_PARAMETER);
			log.error("已存在该类别行业");
			return null;
		}
		// 删除原先关联存在的ReportType，根据现在选择的不在关联的要删除掉.
		if (noReportTypes != null && noReportTypes.length > 0) {
			Filter filter = new Filter();
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "industry.id", industry.getId()));
			filter.addRule(new FilterRule(FilterConstant.COLLECTION, "reportTypeId", noReportTypes));

			List<DustryReport> dustryReports = dustryReportDAO.find(DustryReport.class, filter, null);
			for (DustryReport dustryReport : dustryReports) {
				dustryReportDAO.delete(dustryReport);
			}
		}
		if (reportTypes != null && reportTypes.size() > 0) {
			String[] deleDustryReport = new String[reportTypes.size()];

			// 将要添加的报表类型保存
			// 先删除现在要保存的报表类型，避免重复
			ReportType rType = new ReportType();
			for (int i = 0; i < reportTypes.size(); i++) {
				rType = reportTypes.get(i);
				deleDustryReport[i] = rType.getId();
			}
			if (deleDustryReport.length > 0) {
				Filter filter = new Filter();
				filter.addRule(new FilterRule(FilterConstant.EQUAL, "industry.id", industry.getId()));
				filter.addRule(new FilterRule(FilterConstant.COLLECTION, "reportTypeId", deleDustryReport));

				List<DustryReport> dustryReports = dustryReportDAO.find(DustryReport.class, filter, null);
				for (DustryReport dustryReport : dustryReports) {
					dustryReportDAO.delete(dustryReport);
				}
			}
		}

		Set<DustryReport> dustryReportSet = new HashSet<DustryReport>();
		if (reportTypes != null && reportTypes.size() > 0) {
			for (ReportType reportType : reportTypes) {
				DustryReport dustryReport = new DustryReport(UUID.randomUUID().toString().replaceAll("-", ""), industry, reportType.getId());
				dustryReportDAO.save(dustryReport);
				dustryReportSet.add(dustryReport);
			}
			industry.setDustryReports(dustryReportSet);
		}
		industryDAO.update(industry);

		return industry;
	}

	public Industry queryIndustryById(String id) {
		if (id != null) {
			return industryDAO.get(Industry.class, id);
		}
		return null;
	}

	public Result queryIndustries(Filter filter, Page page) {
		List<Industry> industries = industryDAO.find(Industry.class, filter, page);
		int count = industryDAO.count(Industry.class, filter);

		if (page == null) {
			return new Result(1, 1, count, industries, new ArrayList<Event>());
		}
		return new Result(page.getPageNumber(), page.getPageSize(), count, industries, new ArrayList<Event>());
	}

	public Result queryIndustriesByhql(String hql, HashMap map, Page page) {
		return industryDAO.hqlParam(hql, map, page);
		// int count = industryDAO.count(Industry.class, filter);
		//
		// if (page == null) {
		// return new Result(1, 1, count, industries, new ArrayList<Event>());
		// }
		// return new Result(page.getPageNumber(), page.getPageSize(), count,
		// industries, new ArrayList<Event>());
	}

	public void removeIndustries(String[] ids) {
		if (ids == null || ids.length < 1) {
			// throw new
			// CommonException(ExceptionConstant.MSG_ILLEGAL_PARAMETER);
			return;
		}

		// 删除DustryReport对象
		Filter filter = new Filter();
		filter.addRule(new FilterRule(FilterConstant.COLLECTION, "industry.id", ids));

		List<DustryReport> dustryReports = dustryReportDAO.find(DustryReport.class, filter, null);
		dustryReportDAO.delete(dustryReports);

		// 删除UserIndustry对象
		Filter filter2 = new Filter();
		filter2.addRule(new FilterRule(FilterConstant.COLLECTION, "industry.id", ids));

		List<UserIndustry> userIndustry = userIndustryDAO.find(UserIndustry.class, filter2, null);
		userIndustryDAO.delete(userIndustry);
		// 删除EnterpriseIndustry对象
		Filter filter3 = new Filter();
		filter3.addRule(new FilterRule(FilterConstant.COLLECTION, "industry.id", ids));

		List<EnterpriseIndustry> enterIndustry = enterpriseIndustryDAO.find(EnterpriseIndustry.class, filter3, null);
		enterpriseIndustryDAO.delete(enterIndustry);

		filter.getRules().clear();
		filter.addRule(new FilterRule(FilterConstant.COLLECTION, "id", ids));

		List<Industry> industries = industryDAO.find(Industry.class, filter, null);
		industryDAO.delete(industries);
	}

	private Industry checkIndustryName(String dustryName) {
		Filter filter = new Filter();
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "dustryName", dustryName));

		List<Industry> industries = industryDAO.find(Industry.class, filter, null);
		if (industries.size() > 0) {
			return industries.get(0);
		}
		return null;
	}

	public List<DustryReport> queryDustryReport(String industryId){
		Filter filter = new Filter();
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "industry.id", industryId));
		return dustryReportDAO.find(DustryReport.class, filter, null);
	}
}
